import JSONAPISerializer from "json-api-serializer"
import request from "../../utils/request";
import flarum from "../../flarum";
import {urlEncode} from "../../utils/tools";
import {formatOptions} from "../../utils/util";

export class Notifications {

    constructor() {
        this.serializer = new JSONAPISerializer()
        this.serializer.register("notifications", {
            id: "id",
            relationships: {
                users: {
                    type: "users"
                },
                posts: {
                    type: "posts"
                },
                discussions: {
                    type: "discussions"
                }
            },
            topLevelMeta: function(data, extraData) {
                return {
                    count: extraData.count,
                    total: data.length
                };
            }
        })

        this.serializer.register('users', {
            type: "users",
            id: "id"
        })

        this.serializer.register('posts', {
            type: "posts",
            id: "id"
        })

        this.serializer.register('discussions', {
            type: "discussions",
            id: "id"
        })
    }

    /**
     * 获取API地址
     * @returns {string}
     */
    getApi(offset = 0){
        return `${flarum.api}/notifications?${urlEncode('page[offset]')}=${offset}`
    }

    execute(func) {
        const that = this
        request.get(that.getApi()).then(res => {
            that.data = res
            that.viewdata = that.serializer.deserialize("notifications", res)
            that.options = formatOptions(that.data)
            func(that.data, that.viewdata, that.options)
        }).catch(res => {})
    }
}